﻿using System.Collections.Generic;
using UnityEngine;

namespace Core
{
    public class EffectComponent : Entity 
    {
        private Dictionary<string, EffectInfo> dict = new Dictionary<string, EffectInfo>();
        public void Create(int effectId, Transform target = default, string key = default)
        {
            Create(effectId,Vector3.zero, Vector3.one, Vector3.zero, target, key);
        }
        public void Create(int effectId, Vector3 position, Vector3 scale, Vector3 rotation, Transform target = default, string key = default)
        {
            var config = World.GetComponent<ConfigComponent>().GetConfig<EffectConfig>(effectId);
            if (string.IsNullOrEmpty(config.path))
                return;

            var prefab = World.GetComponent<ResourceComponent>().Load<GameObject>(config.path);
            if (prefab == null)
                return;

            if (!string.IsNullOrEmpty(key))
            {
                if (dict.TryGetValue(key, out var obj))
                {
                    obj.Dispose();
                }
            }

            var go = GameObject.Instantiate(prefab);
            if(target != null)
            {
                go.transform.SetParent(target);
            }
            go.transform.position = position + config.position;
            go.transform.rotation = Quaternion.Euler(rotation + config.rotation);
            go.transform.localScale = scale + config.scale;

            Timer timer = default;
            if(config.waitTime > 0)
            {
                timer = World.GetComponent<TimerComponent>().CreateTimer(config.waitTime, () => 
                { 
                    if(!string.IsNullOrEmpty(key))
                    {
                        if (dict.TryGetValue(key, out var obj))
                        {
                            obj.Dispose();
                        }
                    }
                    else
                    {
                        GameObject.Destroy(go);
                    }
                });
            }

            if (!string.IsNullOrEmpty(key))
            {
                dict[key] = new EffectInfo { gameObject = go, timer = timer };
            }
        }
    }
}